package com.dszq.user.service.impl;

import com.dszq.common.constants.BehaviorConstants;
import com.dszq.common.redis.CacheService;
import com.dszq.model.common.dtos.ResponseResult;
import com.dszq.model.common.enums.AppHttpCodeEnum;
import com.dszq.model.user.dtos.UserRelationDto;
import com.dszq.model.user.pojos.ApUser;
import com.dszq.user.service.ApUserRelationService;
import com.dszq.utils.thread.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * [一句话描述该类的功能]
 *
 * @author : [Lenovo]
 * @version : [v1.0]
 * @createTime : [2024/5/2 15:11]
 */
@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private CacheService cacheService;
    /**
     * 处理用户关注操作的请求。
     *
     * @param userRelationDto 包含关注关系信息的数据传输对象，
     * @return 返回一个响应结果，这个结果可以是操作成功与否的提示或相关数据。
     */
    @Override
    public ResponseResult follow(UserRelationDto userRelationDto) {
        //1 参数校验
        if (userRelationDto.getOperation() == null || userRelationDto.getOperation() < 0 || userRelationDto.getOperation() > 1) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtil.getUser();
        if (user==null)
        {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        Integer userId = user.getId();
        Integer authorId = userRelationDto.getAuthorId();
        if (userRelationDto.getOperation() == 0)
        {
            //关注
            //userId成为authorId的粉丝
            cacheService.zAdd(BehaviorConstants.APUSER_FANS_RELATION+authorId,userId.toString(),System.currentTimeMillis());
            //authorId成为userId的关注
            cacheService.zAdd(BehaviorConstants.APUSER_FOLLOW_RELATION+userId,authorId.toString(),System.currentTimeMillis());
        }else {
            //取关
            //authorId的粉丝中删除userId
            cacheService.zRemove(BehaviorConstants.APUSER_FANS_RELATION+authorId,userId.toString());
            //userId的关注中删除authorId
            cacheService.zRemove(BehaviorConstants.APUSER_FOLLOW_RELATION+userId,authorId.toString());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
